// CLIENT PROGRAM 
#include <netdb.h>
#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), sendto(), and recvfrom() */
#include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() */
#include <iostream>
#include "standardPacket.h"	// Contains the struct info
#include "funcs.h"

#define ECHOMAX 255     /* Longest string to echo */
#define MAXSERVERSTR	6	// Longest possible string returned by server
#define TIMEOUT_S 1     // Time in seconds to wait before timeout
#define TIMEOUT_MS 500	// Additional time in ms to wait for timeout 
#define NUM_REQUESTS 20	// Number of times to request service from server

void DieWithError(const char *errorMessage) /* External error handling function */
{
    perror(errorMessage);
    exit(1);
}

int main(int argc, char *argv[])
{   
    // Setup variables
    int sock;                        /* Socket descriptor */
    struct sockaddr_in echoServAddr; /* Echo server address */
    struct sockaddr_in fromAddr;     /* Source address of echo */
    unsigned short echoServPort;     /* Echo server port */
    unsigned int fromSize;           /* In-out of address size for recvfrom() */
    char *servIP;                    /* IP address of server */
    char *echoString;                /* String to send to echo server */
    char echoBuffer[ECHOMAX+1];      /* Buffer for receiving echoed string */
    int echoStringLen;               /* Length of string to echo */
    int respStringLen;               /* Length of received response */
    int clientNum; 

    // Commandline Arguments
    if (argc != 4)              // Ensure correct num of arguments are passed in
    {
        fprintf(stderr,"Usage: %s <Server IP> <Port Number> <Client Number>\n", argv[0]);
        exit(1);
    }

    servIP = argv[1];               // IP Address of server 
    echoServPort = atoi(argv[2]);   // Port Number
    clientNum = atoi(argv[3]);      // Client Num 
    
    /* Create a datagram/UDP socket */
    if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
        DieWithError("socket() failed");
	
	// Configure Socket for Timeout
	struct timeval timeout;
  	timeout.tv_sec = TIMEOUT_S;
  	timeout.tv_usec = TIMEOUT_MS*1000;
  	if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
      		DieWithError("Socket Setup Error");
  	}

    /* Construct the server address structure */
    memset(&echoServAddr, 0, sizeof(echoServAddr));    /* Zero out structure */
    echoServAddr.sin_family = AF_INET;                 /* Internet addr family */
    echoServAddr.sin_addr.s_addr = inet_addr(servIP);  /* Server IP address */
    echoServAddr.sin_port   = htons(echoServPort);     /* Server port */

	Request *myRequest = new Request;
	//const char * tempStr = "000.000.000.000";
	//memcpy(myRequest->client_ip, tempStr, 16);
    gethostname(myRequest->client_ip, 16);
	myRequest->inc = 0;
	myRequest->client = 0;
	myRequest->req = 0;
	myRequest->c = 0;


   	fromSize = sizeof(fromAddr);
	for(int i=0; i<NUM_REQUESTS; i++)
	{
		bool retry = false;
		int incar; 
		incar = getIncarnation(); 
		myRequest->inc = incar;
		myRequest->client = clientNum; 
		myRequest->req = i+1;
		myRequest->c = randChar(); 
		do{		
                std::cout << std::endl << std::endl << "----\tATTEMPT\t----" << std::endl; 	
                std::cout << "Try: " << i+1 << std::endl; 
                std::cout << "Char: " << myRequest->c << std::endl; 
                std::cout << "Status: "; 
    			/* Send the struct to the server */
    		if(randomSuccess(50)){
				if (sendto(sock, myRequest, sizeof(Request), 0, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) != sizeof(Request))
					DieWithError("sendto() sent a different number of bytes than expected");
                    std::cout << "Client Success" << std::endl; 
			}
			else{
				incrementIncarnation();
				std::cout << "Client Failure, New incarnation: " << getIncarnation() << std::endl; 
            }

            std::cout << "Response Status: ";
			if((recvfrom(sock, echoBuffer, ECHOMAX, 0, (struct sockaddr *)&fromAddr, &fromSize)) >= 0){
				retry = false; 
                std::cout << "Server responded with: " << echoBuffer << std::endl; 
            }
			else{
				std::cout << "No/Bad Response, Retrying: "<< i << std::endl; 
				retry = true; 
			}
		}while(retry); 	
	}

    
    close(sock);
    exit(0);
}
